package com.cj.open.auth;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.Duration;

@Controller
@RequestMapping("/auth")
public class AuthController {

    @GetMapping("/login")
    public ResponseEntity<Void> login(HttpServletRequest request, HttpServletResponse response) {

        // 3. 设置Cookie (关键配置)
        ResponseCookie sessionCookie = ResponseCookie
                .from("sessionid", "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6Ijc3Yjk1ZTIxLTUzYjktNGE0Ni05MDA3LTYwNjU1NTJkOTdjMSJ9.4diP95zS8J7WDwouEjt6acf_ZkpzqRKqL8rD6n3Js7mGp3e2Hhud74OlAE-0d0jkO6dp0OBtRpJIJ1zhzXYpzw")
                .domain(null)       // 不设置 domain（IP 无法作为合法 domain）
                .path("/")          // 根路径，覆盖所有接口
                .httpOnly(true)     // 防 XSS
                .secure(false)      // 若为 HTTP 设为 false（生产环境用 HTTPS 设为 true）
                .sameSite("Lax")    // CSRF 防护
                .maxAge(Duration.ofHours(8)) // 会话有效期 8 小时
                .build();

        // 4. 重定向到前端主页
        return ResponseEntity.status(HttpStatus.FOUND)
                .header(HttpHeaders.LOCATION, "https://vue.ruoyi.vip")
                .header(HttpHeaders.SET_COOKIE, sessionCookie.toString())
                .build();
    }
}
